package ch.simplix.android.remoteZapper;

import java.math.BigInteger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import ch.simplix.android.digest.DigestHelper;

public class RemoteZapperIncomingSMSBroadcastReceiver extends BroadcastReceiver {
	private static final BigInteger destructionKey = new BigInteger(
			"9d28ec8a787bd9be46bb26863e6e770a4e5f57f3", 16); // destroyMe
	private static final BigInteger haltKey = new BigInteger(
			"da2d54cee2f6944883dcb5ccb2971173ff512a3a", 16); // stopDestroyMe

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction()
				.equals("android.provider.Telephony.SMS_RECEIVED")) {

			Bundle bundle = intent.getExtras();
			if (bundle == null)
				return;
			Object[] pdus = (Object[]) bundle.get("pdus");
			for (Object pdu : pdus) {
				{
					if (pdu == null)
						continue;
					String msg = SmsMessage.createFromPdu((byte[]) pdu)
							.getMessageBody();
					if (msg == null)
						continue;
					Log.d("Zapper", msg);
					if (DigestHelper.isEqual(msg, destructionKey)
							|| DigestHelper.isEqual(msg, haltKey)) {
						Intent zapperIntent = new Intent(
								"ch.simplix.android.remoteZapper.REMOTE_ZAPPER_SERVICE");
						zapperIntent.putExtra("message", msg);
						Log.d("Zapper", "initiate");
						// Implicit start of RemoteZapperService
						context.startService(zapperIntent);
					}
				}
			}
		}

	}
}
